package com.cs.deviceManager.mqtt.ota;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalNotification;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 基于 Google Guava 的本地 OTA 状态缓存
 * ✅ 真正使用 Guava Cache，支持自动过期、最大容量
 */
@Component
public class OtaLocalCache {

    // ✅ 只保留状态缓存
    private final Cache<String, OtaStatus> statusCache;

    public OtaLocalCache() {
        this.statusCache = CacheBuilder.newBuilder()
                .expireAfterWrite(30, TimeUnit.SECONDS)
                .maximumSize(1000)
                .removalListener((RemovalNotification<String, OtaStatus> notification) -> {
                    // 无需清理日志，日志在 reporter 实例中
                })
                .build();
    }

    public void putStatus(String deviceId, OtaStatus status) {
        statusCache.put(deviceId, status);
    }

    public OtaStatus getStatus(String deviceId) {
        return statusCache.getIfPresent(deviceId);
    }

    public void remove(String deviceId) {
        statusCache.invalidate(deviceId);
    }



    /*// --- 获取完整状态 ---
    public OtaFullStatus getFullStatus(String deviceId) {
        return new OtaFullStatus(getStatus(deviceId), getLogs(deviceId));
    }*/

    // --- 数据类（保持不变）---

    public record OtaStatus(String status, int progress, int currentPacket, int totalPackets, long sentBytes,
                            long firmwareSize, int elapsedTime, long startTime, String errorMessage) {
    }

    public record OtaFullStatus(OtaStatus status, List<String> log) {
    }
}